<template>
    <div class="documentIndex">
        <bread :title="title" :desc="desc"></bread>
        <div class="content">
            <el-upload
                class="upload-pdf"
                drag
                multiple
                accept=".jpg, .jpeg, .png"
                :with-credentials="true"
                :auto-upload="true"
                :action="uploadURL"
                :data="uploadParams"
                :headers="uploadHeaders"
                :before-upload="beforeUpload"
                :on-exceed="uploadExceed"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :limit="3"
            >
                <div class="upload">
                    <div class="dragnone">
                        <div class="box">
                            <el-input v-model="upload" placeholder="将文件拖拽到这里进行上传"></el-input>
                            <el-button type="primary">本地上传</el-button>
                        </div>
                        <span class="tips">支持文件格式：.jpg,.jpeg,.png</span>
                    </div>
                </div>
            </el-upload>
            <div class="handles">
                <div class="right">
                    <searchFile @on-search="onSearch" @on-clear="onClear"></searchFile>
                    <el-date-picker
                        style="margin-left:10px; height:32px"
                        v-model="dateValue"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        @change="dateChange"
                        @clear="clearDate"
                    ></el-date-picker>

                    <!-- <el-button type="primary" id="batch-download" @click="batchDownload">批量下载</el-button> -->
                </div>
            </div>

            <div class="data-table">
                <el-table
                    :data="tableData"
                    ref="multipleTable"
                    tooltip-effect="dark"
                    style="width: 100%"
                    max-height="470"
                    :row-class-name="tableRowClassName"
                    @select="handleSelect"
                    @selection-change="handleSelectionChange"
                    @row-click="handleRowClick"
                    v-loading="loading"
                    element-loading-text="拼命加载中"
                    element-loading-spinner="el-icon-loading"
                >
                    >
                    <el-table-column type="selection" width="50" align="center"></el-table-column>
                    <el-table-column fixed prop="seqNo" label="文件序号" width="120" align="center"></el-table-column>
                    <el-table-column
                        prop="resName"
                        label="文件名"
                        width="320"
                        align="left"
                        :show-overflow-tooltip="true"
                    ></el-table-column>
                    <el-table-column
                        prop="size"
                        label="文件大小"
                        width="120"
                        align="center"
                        :formatter="formatSize"
                    ></el-table-column>
                    <!-- <el-table-column prop="pageSize" label="页数" width="120" align="center"></el-table-column> -->
                    <el-table-column label="处理结果" width="150" align="center">
                        <template slot-scope="scope">
                            <div v-if="scope.row.processCost" class="processing">
                                <span>识别完成</span>
                                <br />
                                <span>
                                    耗时:{{
                                    formatCost(scope.row.processCost)
                                    }}
                                </span>
                            </div>
                            <div v-else class="processing">
                                <span>正在识别</span>
                                <img src="@assets/images/loading_status.gif" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="uploadUser" label="上传者" align="center" width="160"></el-table-column>
                    <el-table-column prop="uploadTime" label="上传日期" align="center" width="180"></el-table-column>
                    <el-table-column
                        label="备注"
                        align="center"
                        width="200"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <div style="cursor: pointer" @click="editRemark(scope.row)">
                                <i class="el-icon-edit"></i>
                                {{ scope.row.remark }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button size="mini" @click="deleteRow(scope.$index, scope.row)">删除</el-button>
                            <el-button size="mini" @click="browser(scope.$index, scope.row)">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="page-block">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                ></el-pagination>
            </div>
        </div>
        <noteDialog
            :currentItem="currentItem"
            :dialogVisible="noteVisible"
            @on-cancel="noteCancel"
            @on-edit="noteHandle"
        ></noteDialog>
        <el-dialog
            :visible.sync="imageDialogVisible"
            :width="dialogWidth"
            :modal="false"
            class="imageDialog"
            :append-to-body="true"
            :open="handleDialogOpen"
            :close="handleDialogClose"
            :destroy-on-close="true"
            ref="imageDialog"
        >
            <identifyContent ref="identify"></identifyContent>
        </el-dialog>
    </div>
</template>

<script>
import searchFile from "@components/common/searchFile.vue";
import noteDialog from "@components/common/noteDialog.vue";
import bread from "@components/common/bread.vue";
import identifyContent from "@views/dashboard/identifyContent.vue";
import { mapState } from "vuex";
export default {
    components: {
        searchFile,
        noteDialog,
        bread,
        identifyContent
    },
    data() {
        return {
            title: "图片识别",
            desc: "仅支持上传jpg,jpeg,png 请上传符合要求的文件",
            tableData: [],
            loading: true,
            total: 0,
            currentPage: this.$api.DEFAULT_PAGE_NUM,
            pageSize: this.$api.DEFAULT_PAGE_SIZE,
            uploadURL: this.$api.IMG_RECO_URL,
            upload: "",
            uploadHeaders: {},
            uploadParams: {},
            currentItem: {},
            dialogVisible: false,
            noteVisible: false,
            multipleSelection: [],
            selectedId: [],
            dateValue: [],
            searchFile: "",
            imageDialogVisible: false,
            dialogWidth: document.documentElement.clientWidth - 50 + "px",
            resId: 0
        };
    },
    computed: {},
    getters: {},
    mounted() {
        this.getUploadList();
        this.$refs.imageDialog.open();
        setTimeout(() => {
            this.$refs.imageDialog.close();
        }, 1000);
    },
    methods: {
        browser(index, tableData) {
            this.imageDialogVisible = true;
            this.resId = tableData.id;
            // console.log("identify", this.$refs.identify);
            this.$refs.identify.loadRecoResult(this.resId);
        },
        handleDialogOpen() {
            console.log("dialog open....");
            debugger;
        },
        handleDialogClose() {
            console.log("dialog close....");
        },
        tableRowClassName({ row, rowIndex }) {
            if ((rowIndex + 1) % 2 === 0) {
                return "even-row";
            }
            return "";
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.getUploadList(this.searchFile, this.dateValue);
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val;
            this.getUploadList(this.searchFile, this.dateValue);
        },
        onSearch(fileName) {
            this.searchFile = fileName;
            this.getUploadList(fileName, this.dateValue);
        },
        onClear() {
            this.searchFile = "";
            this.getUploadList(this.searchFile, this.dateValue);
        },
        beforeUpload() {
            // console.log("before upload");
        },
        uploadExceed(file, filelist) {
            this.$message.err("文件超出个数限制");
        },
        uploadSuccess(res) {
            console.log("upload success", res);
            this.getUploadList(this.searchFile, this.dateValue);
            this.getWebsocket(res.data);
        },
        uploadError(err, file, fileList) {
            console.error("upload error", err);
            const res = JSON.parse(err.message);
            if (res.code === "401") {
                this.$router.push("/login");
            }
        },
        getUploadList(fileName, dateArr = []) {
            let url = this.$api.GET_UPLOAD_LIST;
            const data = {
                fileName: fileName,
                oprType: 2
            };
            if (dateArr && dateArr.length === 2) {
                (data.beginTime = dateArr[0]), (data.endTime = dateArr[1]);
            }
            url = url
                .replace("{pageNum}", this.currentPage)
                .replace("{pageSize}", this.pageSize);
            this.loading = true;
            this.$request
                .get(url, data)
                .then(result => {
                    this.loading = false;
                    if (result.code === this.$api.CODE_SUCCESS) {
                        this.total = result.data.total;
                        this.tableData = result.data.list;
                    }
                })
                .catch(err => {
                    this.loading = false;
                    console.error(err);
                });
        },
        dateChange(dateArr) {
            this.dateValue = dateArr;
            this.getUploadList(this.searchFile, dateArr);
        },
        clearDate() {
            this.dateValue = [];
            this.getUploadList(this.searchFile, this.dateValue);
        },
        getFileName(id) {
            for (let i = 0; i < this.tableData.length; i++) {
                if (id === this.tableData[i].id) {
                    const name = this.tableData[i].resName;
                    return name.slice(0, name.indexOf(".")) + ".zip";
                }
            }
        },
        deleteRow(index, tableData) {
            const id = tableData.id;
            const url = this.$api.DEL_DATA.replace("{id}", id);
            this.$request.get(url).then(res => {
                this.$message.success("删除成功");
                this.getUploadList();
            });
        },
        editRemark(item) {
            this.currentItem = item;
            this.noteVisible = true;
        },
        noteCancel() {
            this.noteVisible = false;
        },
        noteHandle(text) {
            this.noteVisible = false;
            let url = this.$api.UPDATE_REMARK;
            const id = this.currentItem.id;
            url = url.replace("{id}", id);
            const data = {
                remark: text
            };
            this.$request
                .get(url, data)
                .then(res => {
                    this.$message.success("修改成功");
                    this.getUploadList();
                })
                .catch(e => {
                    console.log(e);
                });
        },
        formatSize(row, column) {
            return this.$util.formatValue(row.size);
        },
        handleSelect(rows) {},
        handleSelectionChange(val) {
            this.multipleSelection = val;
            this.getSelectId();
        },
        // 点击行触发，选中或不选中复选框
        handleRowClick(row, column, event) {
            this.$refs.multipleTable.toggleRowSelection(row);
        },
        getSelectId() {
            this.selectedId = [];
            this.multipleSelection.forEach(row => {
                this.selectedId.push(row.id);
            });
        },
        formatCost(val) {
            return this.$util.formatValue(val);
        },
        getWebsocket(id) {
            if (typeof WebSocket === "undefined") {
                console.error("您的浏览器不支持WebSocket");
            } else {
                // console.log("您的浏览器支持WebSocket");
                // 实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
                const url = this.$api.GET_STATUS.replace("{sid}", id);
                const ws = new WebSocket(url);
                // 连接后监听
                ws.onopen = () => {
                    // console.log("websocket 已打开", ws.readyState);
                };
                // 获得消息事件
                ws.onmessage = msg => {
                    if (msg.data === "连接成功") {
                        // console.log("id:" + id + "连接成功");
                    } else {
                        const res = JSON.parse(msg.data);
                        const resId = res.resId;

                        this.tableData.forEach(data => {
                            if (data.id === resId) {
                                data.processCost = res.processCost;
                                data.pageSize = res.pageSize;
                            }
                        });
                    }
                };
                // 监听连接关闭
                ws.onclose = data => {
                    console.log("websocket已关闭", data);
                };
                // 发生了错误事件
                ws.onerror = () => {
                    console.log("websocket发生了错误");
                    // 此时可以尝试刷新页面
                };
            }
        }
    }
};
</script>

<style lang="stylus">
@import './pdf2img.styl';

.el-table {
    .even-row {
        background: #fafafa;
    }
}

.processing {
    height: 50px;
    text-align: center;
    display: block;

    span {
        font-size: 9pt;
        font-weight: 10;
    }

    img {
        width: 100px;
        height: 38px;
        margin-top: -5px;
    }
}

.el-table td {
    padding: 8px 0;
}

#batch-download {
    margin-left: 20px;
    margin-right: 8px;
    border-radius: 4px;
    background: #16336c;
    border-color: #16336c;
    color: #fff;
    height: 32px;
    text-align: center;
}
</style>
